package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DeptTagEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysDiagnosisTask;
import com.ruoyi.system.domain.SysNaire;
import com.ruoyi.system.service.ISysDiagnosisTaskService;
import com.ruoyi.system.service.ISysNaireService;
import com.ruoyi.system.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@Api(tags = "部门信息管理")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDiagnosisTaskService sysDiagnosisTaskService;

    @Autowired
    private ISysNaireService sysNaireService;

    /**
     * 获取部门列表
     */
    @ApiOperation(value = "获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 获取部门列表
     */
    @ApiOperation(value = "分页获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/page")
    public TableDataInfo listPage(SysDept dept)
    {
        startPage();
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @ApiOperation(value = "查询部门列表（排除节点）")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据服务商id获取详细信息
     */
    @ApiOperation(value = "根据部门编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 根据服务商id获取详细信息
     */
    @ApiOperation(value = "根据服务商id获取服务商详情和产品详情")
   // @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/supplier/{deptId}")
    public AjaxResult getSupplierInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.getSupplierByDeptId(deptId));
    }

    /**
     * 根据部门编号获取公司/服务商详细信息
     */
    @ApiOperation(value = "根据部门编号获取公司/服务商详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/company/{deptId}")
    public AjaxResult getCompanyInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        SysDept temp=deptService.selectDeptById(deptId);
        while(true){
            if (temp.getParentId()==0)
                break;
            else
                temp=deptService.selectDeptById(temp.getParentId());
        }
        return AjaxResult.success(temp);
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect/{deptId}")
    public AjaxResult treeselect(@PathVariable Long deptId)
    {
        SysDept dept=new SysDept();
        dept.setDeptId(deptId);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {


        LoginUser user =SecurityUtils.getLoginUser();
        if(!user.getUser().isAdmin()) {
            List<Long> roleIds = roleService.selectRoleListByUserId(user.getUserId());
            if(roleIds!=null&&roleIds.contains(3L))
                dept.setDeptId(deptService.getCompanyByDeptId(user.getDeptId()));
            else
                dept.setDeptId(user.getDeptId());
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());

        return toAjax(deptService.insertDept(dept));
    }


    /**
     * 新增服务商
     */
    @ApiOperation(value = "新增服务商")
   // @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "新增服务商", businessType = BusinessType.INSERT)
    @PostMapping("/supplier")
    public AjaxResult addSupplier(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增服务商'" + dept.getDeptName() + "'失败，服务商名称已存在");
        }
        dept.setCreateBy(getUsername());
        dept.setDeptTag(DeptTagEnum.SUPPLIER.getCode());
        return toAjax(deptService.inserCompany(dept));
    }

    /**
     * 新增企业
     */

    @PreAuthorize("@ss.hasPermi('system:dept:addcomp')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addcomp")
    public AjaxResult addComp(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增公司'" + dept.getDeptName() + "'失败，公司名称已存在");
        }
        dept.setCreateBy(getUsername());
        dept.setDeptTag(DeptTagEnum.COMPANY.getCode());
        int result=deptService.inserCompany(dept);
        SysNaire nqure=new SysNaire();
        nqure.setIsDefault("Y");
        List<SysNaire>defaultNaires=sysNaireService.selectSysNaireList(nqure);

        SysDiagnosisTask sysDiagnosisTask=new SysDiagnosisTask();
        sysDiagnosisTask.setCompanyId(dept.getDeptId());
        sysDiagnosisTask.setOrderNum(0);
        sysDiagnosisTask.setStatus("0");
        if(defaultNaires!=null&&defaultNaires.size()>0){
            SysNaire defaultNaire=defaultNaires.get(0);
            sysDiagnosisTask.setNaireId(defaultNaire.getNaireId());
            sysDiagnosisTask.setCreateBy(getUsername());
            sysDiagnosisTaskService.insertSysDiagnosisTask(sysDiagnosisTask);
        }
        return toAjax(result);
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 修改服务商
     */
    @ApiOperation(value = "修改服务商")
    @Log(title = "修改服务商", businessType = BusinessType.UPDATE)
    @PutMapping("/supplier")
    public AjaxResult editSupplier(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改服务商'" + dept.getDeptName() + "'失败，服务商名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除服务商
     */
    @ApiOperation(value = "删除服务商")
    @Log(title = "删除服务商", businessType = BusinessType.DELETE)
    @DeleteMapping("/supplier/{deptId}")
    public AjaxResult removeSupplier(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("服务商存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }


    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 用户导入
     */
    @Log(title = "公司管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importDeptData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysDept> util = new ExcelUtil<>(SysDept.class);
        List<SysDept> DeptList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = deptService.importDept(DeptList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importDeptTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysDept> util = new ExcelUtil<SysDept>(SysDept.class);
        util.importTemplateExcel(response, "公司数据");
    }


}
